package me.yuzho.study.concurrency;

import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.IntStream;

/** 线程可以驱动任务，使用Runnable接口来描述任务，实现run方法使任务可以执行
 * @author yzhou-citrix
 *
 */
public class ListOff implements Runnable {
    
    private static int taskCount = 0;
    private final int id = taskCount++; //
    
    protected int countDown = 10;
    
    public ListOff() {}
    
    public ListOff(int countDown) {
        this();
        this.countDown = countDown;
    }
    
    public String status() {
        return String.format("#%d(%s)", id, countDown == 0? "Listoff!" : ""+countDown);
    }

    @Override
    public void run() {
        
        while(countDown-- > 0) {
            System.out.println(status());
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    }
    
    public static void main(String [] args) {
        
        /*
        ListOff launch = new ListOff();
        launch.run();*/
        
        /*
        for(int i=0; i<5; i++) {
            new Thread(new ListOff()).start();;
        }
        
        System.out.println("Waitting for lift off");*/
        
        // Use cached thread pool to run tasks
        ExecutorService exec = Executors.newCachedThreadPool();
        
        IntStream.range(0, 5).parallel().forEach(i -> {
            exec.execute(new ListOff());
        });
        
        exec.shutdown();
        
        //exec.execute(new ListOff()); After executor is shutdown, new task could not be added
        
        
        
        
    }

}
